﻿/*
 * 描 述：附件上传管理	
 */
var keyVaule = request('keyVaule');
var extensions = request('extensions');
var isInvoice = request('isInvoice');
var processId = request('processId');

var bootstrap = function ($, learun) {
    "use strict";
    $.lrSetForm(config.base_server() + 'files/list?folderId=' + keyVaule + '&access_token=' + config.getToken().access_token, function (data) {
        for (var i = 0, l = data.length; i < l; i++) {
            $('#lr_form_file_queue .lr-form-file-queue-bg').hide();
            var item = data[i];
            fileInfo[item.id] = {
                fileGuid: item.id,
                chunks: 1
            }
            var $item = $('<div class="lr-form-file-queue-item" id="lr_filequeue_' + item.id + '" ></div>');
            $item.append('<div class="lr-file-image"><img src="/assets/plugins/images/filetype/' + item.ext + '.png"></div>');
            $item.append('<span class="lr-file-name">' + item.name + '(' + learun.countFileSize(item.size) + ')</span>');

            $item.append('<div class="lr-msg"><i class="fa fa-check-circle"></i></div>');
            $item.append('<div class="lr-tool-bar"><i class="fa fa-eye" title="预览"  data-value="' + item.id + '" ></i><i class="fa fa-cloud-download" title="下载"  data-value="' + item.id + '" ></i><i class="fa fa-minus-circle" title="删除"  data-value="' + item.id + '" ></i></div>');

            $item.find('.lr-tool-bar .fa-minus-circle').on('click', function () {
                var fileId = $(this).attr('data-value');
                DeleteFile(fileId);
            });

            $item.find('.lr-tool-bar .fa-cloud-download').on('click', function () {
                var fileId = $(this).attr('data-value');
                DownFile(fileId);
            });
            $item.find('.lr-tool-bar .fa-eye').on('click', function () {
                var fileId = $(this).attr('data-value');
                openViewForm(fileId);
            });
            $('#lr_form_file_queue_list').append($item);
        }
    });

    var fileInfo = {};

    // 触发合并文件碎片
    var mergeFileChunks = function (file) {
        var param = {};

        param['processId'] = processId;
        param['folderId'] = keyVaule;
        param['name'] = fileInfo[file.id].name;
        param['url'] = fileInfo[file.id].url;
        param['id'] = fileInfo[file.id].id;
        param['ext'] = fileInfo[file.id].ext;
        param['size'] = fileInfo[file.id].size;
        if (!!isInvoice && isInvoice == 1) {
            param['isInvoice'] = 1;
        }
        learun.httpAsyncPost(config.base_server() + 'files/save?access_token=' + config.getToken().access_token, JSON.stringify(param), function (res) {
            var $fileItem = $('#lr_form_file_queue_list').find('#lr_filequeue_' + file.id);
            $fileItem.find('.lr-uploader-progress').remove();
            if (res.resp_code == learun.httpCode.success) {
                // 文件保存成功后
                $fileItem.append('<div class="lr-msg"><i class="fa fa-check-circle"></i></div>');
                $fileItem.append('<div class="lr-tool-bar"><i class="fa fa-minus-circle" title="删除"  data-value="' + file.id + '" ></i></div>');

                $fileItem.find('.lr-tool-bar .fa-minus-circle').on('click', function () {
                    var fileId = $(this).attr('data-value');
                    DeleteFile(fileId);
                });
            } else {
                $fileItem.append('<div class="lr-msg"><i class="fa fa-exclamation-circle"></i></div>');
            }
        });
    }

    // 删除文件
    var DeleteFile = function (fileId) {
        var param = {};
        learun.httpAsyncPost(config.base_server() + 'files/delete?id=' + fileId + '&access_token=' + config.getToken().access_token, param, function (res) {
        });
        var file = page.uploader.getFile(fileId);
        if (!!file) {
            page.uploader.removeFile(file);
        }
        delete fileInfo[fileId];
        var $fileItem = $('#lr_form_file_queue_list').find('#lr_filequeue_' + fileId);
        $fileItem.remove();
        if ($('#lr_form_file_queue_list>div').length == 0) {
            $('#lr_form_file_queue .lr-form-file-queue-bg').show();
        }
    }
    // 下载文件
    var DownFile = function (fileId) {
        learun.download({
            url: config.base_server() + 'files/download?id=' + fileId + '&access_token=' + config.getToken().access_token,
            param: {fileId: fileId},
            method: 'POST'
        });
    }
    //预览文件
    var openViewForm = function (fileId) {
        learun.layerForm({
            id: 'PreviewForm',
            title: '文件预览',
            url: config.webportal_server + 'pages/utility/previewFile.html?keyVaule=' + fileId + '&access_token=' + config.getToken().access_token,
            width: 1080,
            height: 850,
            btn: null
        });
    }

    var page = {
        uploader: null,
        init: function () {
            if (!WebUploader.Uploader.support()) {
                alert('Web Uploader 不支持您的浏览器！如果你使用的是IE浏览器，请尝试升级 flash 播放器');
                throw new Error('WebUploader does not support the browser you are using.');
            }

            page.uploader = WebUploader.create({
                auto: true,
                swf: config.webportal_server + '/assets/plugins/webuploader/Uploader.swf',
                // 文件接收服务端。
                server: config.base_server() + 'common/upload?access_token=' + config.getToken().access_token,
                // 选择文件的按钮。可选。
                // 内部根据当前运行是创建，可能是input元素，也可能是flash.
                pick: '#lr_add_file_btn',
                dnd: '#lr_form_file_queue',
                paste: 'document.body',
                disableGlobalDnd: true,
                accept: {
                    extensions: extensions || "gif,jpeg,jpg,png,psd,rar,zip,pdf,doc,docx,ppt,pptx,txt,xls,xlsx"
                },
                // multiple: true,
                // // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
                // resize: false,
                // // 文件分片上传
                // chunked: true,
                // chunkRetry: 3,
                // prepareNextFile: true,
                // chunkSize: '1048576',
                // 上传参数
                formData: {
                    __RequestVerificationToken: $.lrToken
                }
            });
            page.uploader.on('fileQueued', page.fileQueued);
            page.uploader.on('uploadStart', page.uploadStart);
            page.uploader.on('uploadBeforeSend', page.uploadBeforeSend);
            page.uploader.on('uploadProgress', page.uploadProgress);
            page.uploader.on('uploadSuccess', page.uploadSuccess);
            page.uploader.on('uploadError', page.uploadError);
            page.uploader.on('uploadComplete', page.uploadComplete);
            page.uploader.on('error', page.error);


            $('#lr_form_file_queue').lrscroll();

            //高拍仪
            $('#lr_add_gpy_btn').on('click', function () {
                learun.layerForm({
                    id: 'takePhoto',
                    title: '拍照',
                    url: config.webportal_server + 'pages/utility/takePhoto.html?access_token=' + config.getToken().access_token,
                    width: 1000,
                    height: 600,
                    callBack: function (id) {
                        return top[id].acceptClick(function (datas) {
                            if (datas) {
                                var id = guid();
                                fileInfo[id] = {name: "附件" + id};
                                $('#lr_form_file_queue .lr-form-file-queue-bg').hide();
                                // 添加一条文件记录
                                var $item = $('<div class="lr-form-file-queue-item" id="lr_filequeue_' + id + '" ></div>');
                                $item.append('<div class="lr-file-image"><img src="/assets/plugins/images/filetype/' + "png" + '.png"></div>');
                                $item.append('<span class="lr-file-name">' + "附件" + id + '(' + learun.countFileSize(0) + ')</span>');

                                $('#lr_form_file_queue_list').append($item);
                                fileInfo[id].url = datas[0];
                                fileInfo[id].ext = "png";
                                fileInfo[id].size = "0";
                                fileInfo[id].id = id;

                                mergeFileChunks(fileInfo[id]);
                            }
                        });
                    }
                });
            });

        },
        fileQueued: function (file) {// 文件加载到队列
            fileInfo[file.id] = {name: file.name};
            $('#lr_form_file_queue .lr-form-file-queue-bg').hide();
            // 添加一条文件记录
            var $item = $('<div class="lr-form-file-queue-item" id="lr_filequeue_' + file.id + '" ></div>');
            $item.append('<div class="lr-file-image"><img src="/assets/plugins/images/filetype/' + file.ext + '.png"></div>');
            $item.append('<span class="lr-file-name">' + file.name + '(' + learun.countFileSize(file.size) + ')</span>');

            $('#lr_form_file_queue_list').append($item);
        },
        uploadStart: function (file) {
            var $fileItem = $('#lr_form_file_queue_list').find('#lr_filequeue_' + file.id);
            $fileItem.append('<div class="lr-uploader-progress"><div class="lr-uploader-progress-bar" style="width:0%;"></div></div>');
        },
        uploadBeforeSend: function (object, data, headers) {
            // data.chunk = data.chunk || 0;
            // data.chunks = data.chunks || 1;
            // fileInfo[data.id].fileGuid = fileInfo[data.id].fileGuid || WebUploader.Base.guid();
            // data.fileGuid = fileInfo[data.id].fileGuid;
            // fileInfo[data.id].chunks = data.chunks;
        },
        uploadProgress: function (file, percentage) {
            var $fileItem = $('#lr_form_file_queue_list').find('#lr_filequeue_' + file.id);
            $fileItem.find('.lr-uploader-progress-bar').css('width', (percentage * 100 + '%'));
        },
        uploadSuccess: function (file, res) {
            if (res.resp_code == 200) {// 上传成功
                fileInfo[file.id].url = res.data;
                fileInfo[file.id].ext = file.ext;
                fileInfo[file.id].size = file.size;
                fileInfo[file.id].id = guid();
                mergeFileChunks(file);
            }
        },
        uploadError: function (file, code) {
            var $fileItem = $('#lr_form_file_queue_list').find('#lr_filequeue_' + file.id);
            $fileItem.find('.lr-uploader-progress').remove();
            $fileItem.append('<div class="lr-msg"><i class="fa fa-exclamation-circle"></i></div>');
        },
        uploadComplete: function (file) {
        },
        error: function (type) {
            switch (type) {
                case 'Q_TYPE_DENIED':
                    learun.alert.error('当前文件类型不允许上传');
                    break;
            }
            ;
        }
    };
    page.init();
}

function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}

function guid() {
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}